<template>
	<view>
		<!-- 巡检扫码 -->
		<view class="inspection_io">
			<scroll-view scroll-y="true" class="scroll-Y">
				<view class="inspection_header">
					<!-- 					<view class="inspection_text">
						<text>巡检签到地点:</text>
						<text class="text_center">
							位置
						</text>
						<uni-icons @tap="navigateToLocation" type="location" style="font-weight: 400;"
							size="20"></uni-icons>
					</view> -->
					<view class="inspection_text" style="margin-top: 20rpx;">
						<text>巡检签退状态:</text>
						<text class="text_center">{{inspectionisBoll}}</text>
					</view>
				</view>
				<view class="inspection_center">
					<view class="inspection_text"> <text>巡检点位:</text> <text
							class="inspection_text1">（扫描点位二维码进行签到）</text> </view>
					<view class="inspection_list" @tap="collapseFun(item)" :key="index"
						v-for="(item,index) of inspectionData">
						<view class="inspection_list_header">
							<view class="list_header_left">
								{{item.inspectionContent}}
							</view>
							<view class="list_header_right" :style="{'color':item.status == 'Y'? '#007afc':''}">
								{{item.inspectionStatus == 'Y'? '已签到':'未签到'}}
							</view>
						</view>
						<view class="content" v-if="inspectionId == item.inspectionRecordId">
							<view class="inspection_text">
								巡检位置:<text class="text_center">{{item.signInAddr || ''}}</text>
							</view>
							<view class="inspection_text">
								巡检隐患:<text class="text_center"
									v-if="item.pitfall">{{item.pitfall =="Y"?'有隐患':'无隐患'}}</text>
							</view>
							<view class="inspection_text">
								巡检情况:<text class="text_center">{{item.resultContent || ''}}</text>
							</view>
							<view class="inspection_text">
								现场图片:
							</view>
							<view class="" style="display: flex;flex-wrap: wrap;width: 100%;">
								<view :key="idx" v-for="(itm,idx) of item.sceneImgs"
									style="width: 150rpx;height: 150rpx;margin: 4rpx;">
									<image :src="baseUrl+itm" style="width: 150rpx;height: 150rpx;" mode=""></image>
								</view>
							</view>
							<view class="inspection_text" v-if="item.pitfallCorrection == 'Y'">
								整改图片:
							</view>
							<view v-if="item.pitfallCorrection == 'Y'" class=""
								style="display: flex;flex-wrap: wrap;width: 100%;">
								<view :key="idx" v-for="(itm,idx) of item.pitfallCorrectionImgs"
									style="width: 150rpx;height: 150rpx;margin: 4rpx;">
									<image :src="baseUrl+itm" style="width: 150rpx;height: 150rpx;" mode=""></image>
								</view>
							</view>
						</view>

					</view>
					<!-- 				<uni-collapse accordion @change="collapseFun">
						<uni-collapse-item :key="index" v-for="(item,index) of inspectionData" :title="item.title">

						</uni-collapse-item>
					</uni-collapse> -->
				</view>
				<view class="reader-box" v-if="isScaning">
					<view class="reader" id="reader"></view>
				</view>
				<view class="inspection_bottom">

					<view class="bottom_btn" @tap="bottomBtn()">
						扫码巡检
					</view>
				</view>
			</scroll-view>
		</view>

	</view>
</template>

<script>
	import {
		getMyTaskRecordList,
		getGetInfo,
		getInspectionId
	} from '@/apis/modules/inspectionApp';
	import projectConfig from '@/env.config.js';
	import QrScanner from 'qr-scanner';
	import {
		Html5Qrcode
	} from "html5-qrcode";
	export default {
		data() {
			return {
				baseUrl: projectConfig.baseUrl,
				inspectionData: [],
				inspectionId: '',
				inspe: '',
				inspectionisBoll: '未签到',
				planId: '',
				html5QrCode: null,
				isScaning: false,
				cameraId: null,
				scanVal: '',
				scanner: null
			}
		},
		onShow() {
			this.getMyTaskRecordListFun(this.inspe, this.planId)
		},
		onLoad(options) {
			this.inspe = options.id
			this.planId = options.planId
			this.getMyTaskRecordListFun(options.id, options.times)
			this.getInspectionIdFun()
		},
		methods: {
			getInspectionIdFun() {
				getInspectionId(this.inspe).then((res) => {
					console.log(res)
					if (res.data.startTime) {
						this.inspectionisBoll = '已签到'
					} else if (res.data.endTime) {
						this.inspectionisBoll = '已签退'
					}
				})
			},
			getMyTaskRecordListFun(id, times) {
				let parms = {
					inspectionId: id,
					inspectionDate: times
				}
				getMyTaskRecordList(parms).then((res) => {

					this.inspectionData = res.data
					for (let item of this.inspectionData) {
						item.sceneImgs = item.sceneImgs ? item.sceneImgs.split(',') : []
						item.pitfallCorrectionImgs = item.pitfallCorrectionImgs ? item.pitfallCorrectionImgs.split(
							',') : []

					}
				})
			},
			navigateToLocation() {
				uni.openLocation({
					latitude: 39.9042, // 目标地点的纬度，浮点数，范围为-90~90
					longitude: 116.4074, // 目标地点的经度，浮点数，范围为-180~180
					scale: 18, // 缩放比例，范围5~18
					name: '目标位置', // 位置名
					address: '目标详细地址', // 地址的详细说明
					success() {
						console.log('导航启动成功');
					},
					fail(error) {
						console.log('导航启动失败', error);
					}
				});
			},
			async startScan() {
				try {
					const videoElem = this.$refs.videoRef.$el || this.$refs.videoRef;
					this.scanner = new QrScanner(
						videoElem,
						result => {
							uni.showModal({
								title: '扫码结果',
								content: result.data,
								showCancel: false
							});
							this.stopScan();
						}, {
							highlightScanRegion: true,
							highlightCodeOutline: true,
							maxScansPerSecond: 5,
							returnDetailedScanResult: true
						}
					);

					await this.scanner.start();
				} catch (error) {
					console.error('扫码失败:', error);
					uni.showToast({
						title: `扫码失败: ${error.message}`,
						icon: 'none'
					});
				}
			},
			stopScan() {
				if (this.scanner) {
					this.scanner.stop();
					this.scanner = null;
				}
			},
			openQrcode() {
				this.isScaning = true;
				Html5Qrcode.getCameras().then((devices) => {
					if (devices && devices.length) {
						if (devices.length > 1) {
							this.cameraId = devices[1].id;
						} else {
							this.cameraId = devices[0].id;
						}
						this.html5QrCode = new Html5Qrcode('reader');
						this.startInit();
					}
				});
			},
			startInit() {
				const that = this;
				this.html5QrCode.start(
						this.cameraId, // retreived in the previous step.
						{
							facingMode: "environment" //  environment后置摄像头 user前置摄像头
						}, 
						{
							fps: 10, // sets the framerate to 10 frame per second
							qrbox: 250 // sets only 250 X 250 region of viewfinder to
						},
						qrCodeMessage => {
							// uni.showModal({
							// 	title: 'success',
							// 	content: JSON.stringify(qrCodeMessage),
							// 	showCancel: false
							// });
							// do something when code is read. For example:
							if (qrCodeMessage) {
								//成功扫出码qrCodeMessage为扫码内容
								//扫码成功记得关掉摄像
								that.action(qrCodeMessage) //对二维码逻辑处理
								that.stopScan(); //关闭扫码功能
							}

						},
						errorMessage => {
						}
					)
					.catch((err) => {
						// 扫码错误信息
						let message = "";
						if (typeof err == "string") {
							message = "识别失败";
						} else {
							if (err.name == "NotAllowedError") {
								message = "您需要授予相机访问权限！";
							}
							if (err.name == "NotFoundError") {
								message = "这个设备上没有摄像头！";
							}
							if (err.name == "NotSupportedError") {
								message =
									"摄像头访问只支持在安全的上下文中，如https或localhost！";
							}
							if (err.name == "NotReadableError") {
								message = "相机被占用！";
							}
							if (err.name == "OverconstrainedError") {
								message = "安装摄像头不合适！";
							}
							if (err.name == "StreamApiNotSupportedError") {
								message = "此浏览器不支持流API！";
							}
						}
					});
			},
			action(val) {
				this.scanVal = val;
				if(!val){
					return
				}
				let _this = this;
				let arr=val.split("&") 
				uni.showModal({
					title: 'success',
					content: arr[0],
					showCancel: false
				});
				getGetInfo(arr[0], _this.planId).then((dev) => {
					if (dev.code == 200) {
						if (arr[0]) {
							uni.navigateTo({
								url: `/pagesB/inspectionApp/inspectionConfirmation?id=${arr[0]}&planId=${_this.planId}&setId=${_this.inspe}&inspectionRecordId=${dev.data.inspectionRecordId}`
							});
						}
					} else {
						uni.showToast({
							title: '该巡检点不在计划内',
							icon: 'none'
						});
					}
				})

			},
			stopScan() {
				console.log('停止扫码')
				this.isScaning = false;
				if (this.html5QrCode) {
					this.html5QrCode.stop()
						.then((ignore) => {
							console.log("停止扫码", ignore);
						})
						.catch((err) => {
							console.log(err);
							showToast("停止扫码失败");
						});
				}
			},
			bottomBtn() {
				// uni.navigateTo({
				// 	url:`/pagesB/inspectionApp/inspectionConfirmation?id=${8}&PlanId=${13}`
				// });

				// return
				// #ifdef H5
				// this.startScan();
				this.openQrcode()
				// #endif

				// #ifdef APP
				let _this = this
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						let _this = this;
						let arr=res.result.split("&") 
						getGetInfo(arr[0], _this.planId).then((dev) => {
							if (dev.code == 200) {
								if (arr[0]) {
									uni.navigateTo({
										url: `/pagesB/inspectionApp/inspectionConfirmation?id=${arr[0]}&planId=${_this.planId}&setId=${_this.inspe}&inspectionRecordId=${dev.data.inspectionRecordId}`
									});
								}
							} else {
								uni.showToast({
									title: '该巡检点不在计划内',
									icon: 'none'
								});
							}
						})


					}
				});
				// #endif
			},
			collapseFun(item) {
				console.log(item.inspectionRecordId, 11111)
				this.inspectionId = item.inspectionRecordId
			}
		}
	}
</script>

<style scoped lang="scss">
	.inspection_io {
		width: 100%;
	}

	.scroll-Y {
		height: calc(100vh - 60rpx);
	}

	.inspection_list {
		border: 1px solid gainsboro;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-top: 10rpx;
	}

	.list_header_left {
		font-size: 32rpx;
		font-weight: bold;
	}

	.list_header_right {
		font-size: 30rpx;
		font-weight: bold;
	}

	.inspection_list_header {
		display: flex;
		justify-content: space-between;
	}

	.inspection_text {
		font-size: 28rpx;
		padding: 10rpx 0;
		// font-weight: bold;
	}

	.text_center {
		padding-left: 20rpx;
		font-weight: 400;
	}

	.inspection_text1 {
		font-size: 26rpx;
		color: #9e9e9e;
	}

	.inspection_header {
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx 20rpx 0 20rpx;
	}

	.inspection_center {
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx;
	}

	.inspection_bottom {
		position: fixed;
		height: 120rpx;
		width: 100%;
		bottom: 0;
		left: 0;

		.bottom_btn {
			width: 85%;
			margin: auto;
			background-color: #007aff;
			color: white;
			text-align: center;
			padding: 20rpx 0;
			border-radius: 30rpx;
		}
	}
</style>